package com.baijiayun.live.ui.toolbox.questionanswer

import androidx.lifecycle.Observer
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.os.Bundle
import android.view.Gravity
import com.google.android.material.tabs.TabLayout
import androidx.core.content.ContextCompat
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import com.baijiayun.live.ui.R
import com.baijiayun.live.ui.base.BaseDialogFragment
import com.baijiayun.live.ui.base.RouterViewModel
import com.baijiayun.live.ui.base.getRouterViewModel
import com.baijiayun.livecore.context.LPConstants
import com.baijiayun.livecore.utils.LPRxUtils
import com.baijiayun.liveuibase.utils.ThemeDataUtil
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_qa_interactive.*

/**
 * Created by yongjiaming on 2019-10-30
 * Describe:问答交互主页面，分为待回复、待发布、已发布三个tab，老师或助教才这么显示。
 * 每个tab都是QADetailFragment
 */
class QAInteractiveFragment : BaseDialogFragment() {

    private lateinit var viewPager: androidx.viewpager.widget.ViewPager
    private lateinit var tablayout: TabLayout
    private lateinit var questionSendFragment: BaseDialogFragment
    private var routerViewModel: RouterViewModel? = null
    private var customTab: TabLayout.Tab? = null
    private var disposable: Disposable? = null

    override fun init(savedInstanceState: Bundle?, arguments: Bundle?) {
        hideBackground()
        this@QAInteractiveFragment.isCancelable = false
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init(view)
        routerViewModel?.isQaOpen = true
    }

    private fun init(view: View) {
        viewPager = view.findViewById(R.id.qa_viewpager)
        tablayout = view.findViewById(R.id.qa_tablayout)
        tablayout.setTabTextColors(
                ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_main_text_color)
                , Color.WHITE)
//        tablayout.setSelectedTabIndicatorColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
        getRouterViewModel()?.let {
            initViewpager(isAdmin())
        }

        send_qa_btn.background = getInputBG()
        send_qa_btn.setOnClickListener {
            if (!::questionSendFragment.isInitialized) {
                questionSendFragment = QuestionSendFragment.newInstance(GENERATE_QUESTION, "", QADetailFragment.QATabStatus.ToAnswer)
            } else {
                if (questionSendFragment.isAdded) {
                    return@setOnClickListener
                }
                showDialogFragment(questionSendFragment)
            }
        }

        qa_exit_tv.setOnClickListener{
            dismiss()
        }

        routerViewModel?.action2MyQAList?.observe(this, Observer {
            it?.let {
                if (!isAdmin() && tablayout.tabCount > 1) {
                    val tab = tablayout.getTabAt(0)
                    if (tab?.isSelected != true) {
                        tab?.select()
                    }
                }
            }
        })
        routerViewModel?.run {
            disposable = liveRoom.toolBoxVM.observableOfQuestionForbidStatus
                    .observeOn(AndroidSchedulers.mainThread())
                    .filter { liveRoom.currentUser.type == LPConstants.LPUserType.Student
                            || liveRoom.currentUser.type == LPConstants.LPUserType.Visitor }
                    .subscribe {
                        send_qa_btn.text = if(it) getString(R.string.live_qa_forbid_tip) else getString(R.string.live_qa_tip)
                        send_qa_btn.isEnabled = !it
                    }
        }
    }

    private fun getInputBG(): Drawable {
        val rstDrawable = StateListDrawable()
        rstDrawable.addState(IntArray(1, init = {android.R.attr.state_enabled})
                , DrawableBuilder()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_bg_color))
                .cornerRadius(context!!.resources!!.getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .strokeColor(ContextCompat.getColor(context!!, R.color.base_bg_stroke))
                .strokeWidth(1)
                .build())
        rstDrawable.addState(IntArray(1, init = {-android.R.attr.state_enabled})
                , DrawableBuilder()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_window_bg_color))
                .cornerRadius(context!!.resources!!.getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .strokeColor(ContextCompat.getColor(context!!, R.color.base_bg_stroke))
                .strokeWidth(1)
                .build())
        return rstDrawable
    }

    private fun isAdmin() = routerViewModel?.liveRoom?.isTeacherOrAssistant == true || routerViewModel?.liveRoom?.isGroupTeacherOrAssistant == true

    override fun getLayoutId() = R.layout.fragment_qa_interactive

    override fun setWindowParams(windowParams: WindowManager.LayoutParams?) {
        if (windowParams != null) {
            context?.let {
                dialog!!.window!!.setBackgroundDrawable(ContextCompat.getDrawable(it, R.drawable.shape_window_common_bg))
                windowParams.width = resources.getDimension(R.dimen.qa_window_width).toInt()
                windowParams.height = resources.getDimension(R.dimen.qa_window_height).toInt()
                windowParams.gravity = Gravity.CENTER;
            }
        }
    }

    override fun hasWindowAnim(): Boolean {
        return false
    }

    private fun initViewpager(showThreeTabs: Boolean = false) {
        if (showThreeTabs) {
            val fragmentList = mutableListOf(QADetailFragment.newInstance(QADetailFragment.QATabStatus.ToAnswer),
                    QADetailFragment.newInstance(QADetailFragment.QATabStatus.ToPublish), QADetailFragment.newInstance(QADetailFragment.QATabStatus.Published))

            viewPager.offscreenPageLimit = 2
            viewPager.adapter = object : androidx.fragment.app.FragmentStatePagerAdapter(childFragmentManager) {
                override fun getItem(position: Int) = fragmentList[position]
                override fun getCount() = fragmentList.size
                override fun getPageTitle(position: Int): CharSequence? {
                    return when (position) {
                        0 -> {
                            context?.resources?.getString(R.string.qa_to_answer) ?: ""
                        }
                        1 -> {
                            context?.resources?.getString(R.string.qa_to_publish) ?: ""
                        }
                        2 -> {
                            context?.resources?.getString(R.string.qa_published) ?: ""
                        }
                        else -> {
                            ""
                        }
                    }
                }
            }
            tablayout.setupWithViewPager(viewPager)
        } else {
            val fragmentList = mutableListOf(QADetailFragment.newInstance(QADetailFragment.QATabStatus.AllStatus),
                    QADetailFragment.newInstance(QADetailFragment.QATabStatus.Published))
            viewPager.adapter = object : androidx.fragment.app.FragmentStatePagerAdapter(childFragmentManager) {
                override fun getItem(position: Int) = fragmentList[position]
                override fun getCount() = fragmentList.size
                override fun getPageTitle(position: Int): CharSequence? {
                    return when (position) {
                        0 -> {
                            context?.resources?.getString(R.string.live_qa_my_answer) ?: ""
                        }
                        1 -> {
                            context?.resources?.getString(R.string.live_qa_student_published) ?: ""
                        }
                        else -> {
                            ""
                        }
                    }
                }
            }
            tablayout.setupWithViewPager(viewPager)
            customTab = tablayout.getTabAt(1)
            customTab?.setCustomView(R.layout.bjy_layout_tab_qa)
            customTab?.customView?.findViewById<TextView>(R.id.qa_tab_tv)?.setTextColor(ThemeDataUtil.getColorSelectWhite2MainText(context))
            viewPager.addOnPageChangeListener(object : androidx.viewpager.widget.ViewPager.OnPageChangeListener{
                override fun onPageScrollStateChanged(p0: Int) {
                    // do nothing
                }

                override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {
                    // do nothing
                }

                override fun onPageSelected(position: Int) {
                    if (position == 1) {
                        routerViewModel?.hasNewQaPublished?.value = false
                    }
                }
            })
        }
        routerViewModel?.hasNewQaPublished?.observe(this, Observer {
            it?.let {
                customTab?.customView?.findViewById<View>(R.id.qa_tab_tip)?.visibility =
                        if (it && customTab?.isSelected != true) View.VISIBLE else View.INVISIBLE
            }
        })
    }

    private fun isActivityFinish() = activity?.run {
        isFinishing || isDestroyed
    } ?: true

    private fun showDialogFragment(dialogFragment: BaseDialogFragment) {
        //添加activity判断，保证fragment中mHost!=null
        if (isActivityFinish()) {
            return
        }
        val ft = childFragmentManager.beginTransaction()
        dialogFragment.show(ft, dialogFragment.javaClass.simpleName + dialogFragment.hashCode())
        childFragmentManager.executePendingTransactions()
        dialogFragment.dialog?.setOnDismissListener(DialogInterface.OnDismissListener {
            if (isActivityFinish() || isDetached) return@OnDismissListener
            val prev = childFragmentManager.findFragmentByTag(dialogFragment.javaClass.simpleName + dialogFragment.hashCode())
            val ftm = childFragmentManager.beginTransaction()
            prev?.let {
                ftm.remove(it)
            }
            ftm.commitAllowingStateLoss()
        })
    }

    fun setViewMode(routerViewModel: RouterViewModel) {
        this.routerViewModel = routerViewModel
    }

    override fun onDestroyView() {
        routerViewModel?.isQaOpen = false
        viewPager.clearOnPageChangeListeners()
        LPRxUtils.dispose(disposable)
        super.onDestroyView()
    }
}